package com.android.commonlib;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

import com.android.commonlib.netlib.CacheManager;
import com.facebook.stetho.Stetho;

import java.util.List;

public abstract class BaseApplication extends Application {

    public static long delta;

    public static Context context ;

    @Override
    public final void onCreate() {
        super.onCreate();

        context = this ;
        Stetho.initializeWithDefaults(this);
        if (isMainProcess()) {
            initOnMainProcess();
        } else {
            initOnOtherProcess();
        }
        CacheManager.getInstance().initCacheDir();

        initAlways();

    }

    private boolean isMainProcess() {
        int pid = android.os.Process.myPid();
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = manager.getRunningAppProcesses();

        if (runningProcesses != null && !runningProcesses.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.pid == pid) {
                    String currentProcessName = processInfo.processName;
                    String mainProcessName = getPackageName();
                    return mainProcessName.equals(currentProcessName);
                }
            }
        }
        return false;
    }

    protected abstract void initOnMainProcess();

    protected abstract void initOnOtherProcess();

    /**
     * 不管是否主进程都要初始化的东西放在这里
     */
    protected abstract void initAlways();

}
